package com.dogegg.lbblog.support;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Stack;

public class LogRecordContext {

    private static final InheritableThreadLocal<Stack<Map<String, Object>>> VARIABLE_MAP_THREAD_LOCAL = new InheritableThreadLocal<>();

    private static Map<String, Object> getVariables() {
        return VARIABLE_MAP_THREAD_LOCAL.get().firstElement();
    }

//    public static final String START_TIME = "__start_time";
//    public static final String END_TIME = "__end_time";

    public static boolean isSpan(){
       return VARIABLE_MAP_THREAD_LOCAL.get() != null;
    }

    public static void span() {
        Stack<Map<String, Object>> stack = null;
        if(VARIABLE_MAP_THREAD_LOCAL.get() == null ) {
            stack = new Stack<>();
            stack.push(new LinkedHashMap<>());
            VARIABLE_MAP_THREAD_LOCAL.set(stack);
        }else{
            VARIABLE_MAP_THREAD_LOCAL.get().push(new LinkedHashMap<>());
        }
    }

//    public static void start(){
//        LogRecordContext.getVariables().put(LogRecordContext.START_TIME,System.currentTimeMillis());
//    }
//
//    public static void end(){
//        LogRecordContext.getVariables().put(LogRecordContext.END_TIME, System.currentTimeMillis());
//    }

    public static void put(String key,Object value){
        if(LogRecordContext.isSpan()){
            LogRecordContext.getVariables().put(key,value);
        }
    }

    public static Map<String, Object> getVariableValues(){
        HashMap result = new LinkedHashMap();
        result.putAll(getVariables());
        return result;
    }

    public static void clear() {
        VARIABLE_MAP_THREAD_LOCAL.get().pop();
    }
}
